package asia.lxq.cic.filter;

import asia.lxq.cic.config.GlobalConfig;
import asia.lxq.cic.entity.LoginUser;
import asia.lxq.cic.entity.Result;
import asia.lxq.cic.entity.StatusCode;
import asia.lxq.cic.entity.User;
import asia.lxq.cic.util.RedisUtil;
import asia.lxq.cic.util.TokenUtil;
import com.auth0.jwt.interfaces.Claim;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ObjectMapper objectMapper;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
//        byte[] allBytes = request.getInputStream().readAllBytes();
//        System.out.println(new String(allBytes, StandardCharsets.UTF_8));
        String token = request.getHeader("Authorization");
        if (token==null||token.equals("")){
            filterChain.doFilter(request,response);
            return;
        }
        token=token.replace("Bearer ", "");
        Map<String, Claim> claimMap;
        try {
            claimMap= TokenUtil.verifyToken(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
            Result<Object> resultMsg = Result.buildOrigin(StatusCode.ILLEGAL_TOKEN,null, "非法的token",false);
            String resultJson = objectMapper.writeValueAsString(resultMsg);
            response.setContentType("application/json;utf-8");
            response.getOutputStream().write(resultJson.getBytes(StandardCharsets.UTF_8));
            return;
        }
        User user= (User) redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+claimMap.get("userId").asString());
        if (user==null){
            throw new RuntimeException("用户未登录");
        }
        LoginUser loginUser=new LoginUser(user);
        if (!loginUser.isEnabled()){
            throw new RuntimeException("账号已被禁用");
        }
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(user.getUserId(),user.getUsername(),loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
